<?php

$menu;

class Admin_My_Controller extends CI_Controller {

    protected $offset;
    protected $nextPage;
    protected $colPage;
    protected $action;
    protected $log_event = "";
    protected $log_data = "";
    protected $use_db_replika = false;
    protected $db_audit;

    function __construct() {
        parent::__construct();


        if($this->input->get("development") == 2 || $this->input->get("development") == 1)echo "<br/><br/><br/><br/>";

        if (!$this->userauth->is_logged()) {
            $last_url = $this->encrypt->encode(current_url() . "?" . $_SERVER["QUERY_STRING"]);

            redirect('admin/index?' . $last_url);
        }

        $this->cek_hak_akses();

        if($this->use_db_replika) {
            $this->db->close();
            $this->db = $this->load->database("replika", true);
        }

        $this->db_audit = $this->load->database("default", true);

        $this->getPostInfo();
    }

    public function striPosCek($linkString, $arrTest) {
        foreach ($arrTest as $value) {
            if (false !== stripos($linkString, $value)) {
                return true;
            }
        }

        return false;
    }

    public function getReadActionSuffix() {
        $result = array();
        $result = $this->db->query("SELECT item FROM read_action_suffix order by id_ras asc");
        return $result->result();
    }

    public function getModifyActionSuffix() {
        $result = array();
        $result = $this->db->query("SELECT item FROM modify_action_suffix order by id_mas asc");
        return $result->result();
    }

    public function getDeleteActionSuffix() {
        $result = array();
        $result = $this->db->query("SELECT item FROM delete_action_suffix order by id_das asc");
        return $result->result();
    }

    public function cek_hak_akses() {
        global $menu;

        $controller_name = $this->uri->segment(1);
        $method_name = $this->uri->segment(2);
        $id_user = $this->userauth->getUserID();
        $this->id_user = $id_user;

        $id_divisi = $this->db->query("SELECT a.id_divisi FROM mt_karyawan a LEFT JOIN mt_user b ON a.nik = b.nik WHERE b.id_user = '$id_user'");
        $id_divisi = $id_divisi->row();

        $id_menu = $this->find_menu_id($controller_name, $method_name);        
        if ($id_menu == "" || $id_menu == 12 ) { // 271: ubah password
            $is_allow = true;
            return "";
        }
        define("IDDIVISI", $id_divisi->id_divisi);

        $menu = $this->db->query("SELECT * FROM mt_menu WHERE id_menu = $id_menu")->row();

        //// super user akses all
        if($id_divisi->id_divisi == 4) {
            $is_allow = true;
        } else {
            $action_type = $this->find_action_type($method_name);

            $this->id_menu = $id_menu;

            $is_allow = false;
            
            if (!$is_allow && isset($_SESSION[USER_AUTH . 'read_granted'])) {
                foreach ($_SESSION[USER_AUTH . 'read_granted'] as $key => $akses) {                    
                    if ($key == $id_menu && $action_type == "read" && $akses == 1) {                        
                        $is_allow = true;                        
                    }
                }
            }

            if (!$is_allow && isset($_SESSION[USER_AUTH . 'modify_granted'])) {
                foreach ($_SESSION[USER_AUTH . 'modify_granted'] as $key => $akses) {
                    if ($key == $id_menu && $action_type == "modify" && $akses == 1) {
                        $is_allow = true;
                    }
                }
            }

            if (!$is_allow && isset($_SESSION[USER_AUTH . 'delete_granted'])) {
                foreach ($_SESSION[USER_AUTH . 'delete_granted'] as $key => $akses) {
                    if ($key == $id_menu && $action_type == "delete" && $akses == 1) {
                        $is_allow = true;
                    }
                }
            }
            
            if($controller_name == "popup") {
                $is_allow = true;
            }
            
            if(!$is_allow) {
                header("location:" . base_url() . "index.php/error");
                exit();
            }
        }
    }

    function find_menu_id($controller_name, $method_name) {        
        foreach ($_SESSION[USER_AUTH . "menu"]["resultMenu"] as $main_menu) {            
            foreach ($main_menu as $menu) {                
                $method_name = $this->sanitize_action($method_name);                
                if (preg_match("#index.php/$controller_name/$method_name#i", rtrim($menu->link, "/"))) {
                    $this->use_db_replika = $menu->use_db_replika;
                    return $menu->id_menu;
                }
            }
        }
    }

    function sanitize_action($method_name) {

        foreach ($this->getReadActionSuffix() as $suffix) {

            $method_name = preg_replace("#$suffix->item$#i", "", $method_name);
        }

        foreach ($this->getModifyActionSuffix() as $suffix) {
            $method_name = preg_replace("#$suffix->item$#i", "", $method_name);
        }

        foreach ($this->getDeleteActionSuffix() as $suffix) {
            $method_name = preg_replace("#$suffix->item$#i", "", $method_name);
        }

        return $method_name;
    }

    function find_action_type($method_name) {
        foreach ($this->getReadActionSuffix() as $suffix) {
            if (preg_match("#$suffix->item$#i", $method_name)) {
                return "read";
            }
        }

        foreach ($this->getModifyActionSuffix() as $suffix) {
            if (preg_match("#$suffix->item$#i", $method_name)) {
                return "modify";
            }
        }

        foreach ($this->getDeleteActionSuffix() as $suffix) {
            if (preg_match("#$suffix->item$#i", $method_name)) {
                return "delete";
            }
        }

        return "read";
    }

    public function setFilterString($array = array()) {
        $data = array();
        $field_name = array();
        $field_title = array();
        $field_type = array();

        if (is_array($array)) {
            foreach ($array as $key => $ar) {
                $field_title[$key] = $ar[0];
                $field_name[$key] = $ar[1];
                $field_type[$key] = $ar[2];
            }

            $fp = new FilterPanel(base_url() . 'index.php/', $field_name, $field_title, $field_type);
            $data['where'] = $fp->getFilterString();
            $data['filterPanel'] = $fp->drawfilterpanel();
            $data['filterPanelSingle'] = $fp->drawfilterpanelsingle();
            $data['dp'] = new jDatePicker();

            return $data;
        }
        else {
            return '';
        }
    }

    public function isKeySegmentExist($text = '') {
        if ('' != $text) {
            $segs = $this->uri->segment_array();
            foreach ($segs as $segment) {
                if (strtolower($segment) == strtolower($text)) {
                    return true;
                }
            }
        }

        return false;
    }

    public function controllerActionName() {
        return $classThis = $this->router->class . '/' . $this->router->method;
    }

    public function getPostInfo() {
        $page = array();

        $this->offset = $this->input->get_post('os');
        $this->nextPage = $this->input->get_post('np');
        $this->colPage = $this->input->get_post('cp');

        if ($this->offset == "") {
            $this->offset = 0;
        }

        if ($this->nextPage == "") {
            $this->nextPage = 1;
        }

        if ($this->colPage == "") {
            $this->colPage = 1;
        }

        $page['offset'] = $this->offset;
        $page['nextPage'] = $this->nextPage;
        $page['colPage'] = $this->colPage;

        return $page;
    }

    public function getPost($action) {
        return $this->input->get_post($action);
    }

    public function export($queryExport, $filename = "") {
        if ('' != $queryExport) {
            $this->load->dbutil();
            $query = $this->db->query($queryExport);
            $delimiter = ",";
            $newline = "\r\n";
            $queryResult = $this->dbutil->csv_from_result($query, $delimiter, $newline);
            $dateNow = date('Y-m-d_H-i-s');
            
            if($filename == "")
                $filename = $this->controllerActionName() . '_' . $dateNow . '.csv';
            
            file_put_contents($filename, $queryResult);
            force_download($filename, $queryResult);
        }
    }

    public function fileAttach($queryExport, $nama) {
        $this->load->helper('file');

        if ('' != $queryExport) {
            $this->load->dbutil();
            $query = $this->db->query($queryExport);
            $delimiter = ",";
            $newline = "\r\n";
            $queryResult = $this->dbutil->csv_from_result($query, $delimiter, $newline);
            $dateNow = date('d-m-Y_H-i-s');
            $url = './export/';
            $nama = str_replace(" ", "_", $nama);
            $saveFile = $url . 'settlement_' . $nama . '_' . $dateNow . '.csv';
            $fileName = 'settlement_' . $nama . '_' . $dateNow . '.csv';

            if (!write_file($saveFile, $queryResult)) {
                return "Gagal Membuat File Settlement.";
            }
            else {
                return $fileName;
            }
        }
    }
    
    public function isExportKeyExist() {
        if ($this->isKeySegmentExist('exp')) {
            return true;
        }
        else if ('exp' == $this->getPost('act')) {
            return true;
        }

        return false;
    }

    public function exportLastQuery($queryExport = '') {
        if ('' == $queryExport and isset($_SESSION[USER_AUTH . 'last_query_' . $this->controllerActionName(false)])) {
            $queryExport = $_SESSION[USER_AUTH . 'last_query_' . $this->controllerActionName(false)];
        }
        else if ('' == $queryExport and isset($_SESSION[USER_AUTH . 'last_query'])) {
            $queryExport = $_SESSION[USER_AUTH . 'last_query'];
        }

        if ('' != $queryExport and $this->isExportKeyExist()) {
            $this->load->dbutil();
            $query = $this->db->query($queryExport);
            $queryResult = $this->dbutil->csv_from_result($query);
            $dateNow = date('Y-m-d_H-i-s');

            force_download(str_replace('/', '_', $this->controllerActionName()) . '_' . $dateNow . '.csv', $queryResult);
        }

        return true;
    }

    public function breadCrumb($set = true) {
        $childMenu = $this->getTitleParentByUri($this->controllerActionName());
        $parentMenu = $this->getTitlePageByUri($this->controllerActionName());

        $breadcrumb_data = array(
                "Home" => base_url(),
                $parentMenu => "#",
                $childMenu => current_url()
        );

        return (true == $set ? $this->generalfunction->generatebreadcrumb($breadcrumb_data) : '');
    }

    public function getPageTitle() {
        $childMenu = $this->getTitleParentByUri($this->controllerActionName());
        return $childMenu;
    }

    public function getMenu() {
        return $this->userauth->getMenu();
    }

    public function getTitleParentByUri($uri = '') {
        if ('' != $uri) {
            $array = $this->userauth->getMenu();
//            print_r($array);

            for ($i = 0; $i <= count($array['namamenu']); $i++) {
                if(isset($array['namamenu'][$i])) {
                    if (isset($array['havechild'][$array['namamenu'][$i]]) && $array['havechild'][$array['namamenu'][$i]] > 0) {
                        foreach ($array['resultMenu'][$array['namamenu'][$i]] as $row) {
                            if (false !== strpos($row->link, $uri)) {
                                $case= array(259,260,261,262);
                                if(in_array($row->id_menu,$case)) {
                                    $menu = "Kas Bank";
                                }else {
                                    $menu = $row->menu;
                                }
                                return $menu;
                            }
                        }
                    }
                }
            }
        }
        else {
            return '';
        }
    }

    public function getTitlePageByUri($uri = '') {
        if ('' != $uri) {
            $array = $this->userauth->getMenu();
            for ($i = 0; $i <= count($array['namamenu']); $i++) {
                if(isset($array['namamenu'][$i])) {
                    if (isset($array['havechild'][$array['namamenu'][$i]]) && $array['havechild'][$array['namamenu'][$i]] > 0) {
                        foreach ($array['resultMenu'][$array['namamenu'][$i]] as $row) {
                            if (false !== strpos($row->link, $uri)) {
                                return $array['namamenu'][$i];
                            }
                        }
                    }
                }
            }
        }
        else {
            return '';
        }
    }

    public function loadMenuDML($page, $data = array()) {

        $datamenu = $this->getMenu();
        $datamenu['pageTitle'] = $this->getPageTitle(true);
        $this->load->view('template/header_dml', $datamenu);
        $this->load->view('template/menu', $datamenu);
        $this->load->view('template/name', $datamenu);
        $this->load->view($page, $data);
        $this->load->view('template/footer');
    }
    public function loadMenuExport($page, $data = array()) {
        $this->load->view('template/header_export', $data);
        $this->load->view($page, $data);
    }

    public function loadMenu($page, $data = array()) {

        $datamenu = $this->getMenu();
        $datamenu['pageTitle'] = $this->getPageTitle(true);
        $this->load->view('template/header', $datamenu);
        $this->load->view('template/menu', $datamenu);
        $this->load->view('template/name', $datamenu);
        $this->load->view($page, $data);
        $this->load->view('template/footer');
    }

    public function getKode($path) {
        $arr = array();
        $load = new LoadPage($path);
        $arr['page'] = "depan";
        $arr['mode'] = "index";

        if ($load->get_page() != "") {
            $arr['page'] = $load->get_page();
        }

        if ($load->get_mode() != "") {
            $arr['mode'] = $load->get_mode();
        }

        $arr['code'] = $load->get_code();

        return $arr;
    }

    public function generatebreadcrumb($isi) {
        $delim = "&nbsp;&#8250;&nbsp;";
        $out = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"width:100%\">";
        $out .= "<tr>";
        $out .= "<td id=\"breadcrumb\">";
        $i = 0;

        foreach ($isi as $key => $value) {
            $out .= $i > 0 ? $delim : "";
            $out .= "<a href=\"" . $value . "\" >" . $key . "</a>";
            $i++;
        }

        $out .= "</td>";
        $out .= "</tr>";
        $out .="</table>";

        return $out;
    }

    public function loadMenuNoHeader($menu, $data) {
        $this->load->view('/template/noheader_popup');

        $this->load->view($menu, $data);
    }

    public function loadMenuHeaderPopup($menu, $data) {
        $this->load->view('/template/header_popup');

        $this->load->view($menu, $data);
    }

    public function MakePagingPage($query, $offset, $colPage, $nextPage) {
        $paging = array();

        $paging['result'] = $this->general_model->getAllDataToolAdmin($query);
        $paging['pagingView'] = $this->paging->createPage($paging['result']['numRows'], $offset, PAGES_LIMIT, $nextPage, 10, $colPage);

        return $paging;
    }

    public function MakePagingPage2($sum, $offset = '', $colPage = '', $nextPage = '') {
        $offset = Generic::fillItIfEmpty($offset, $this->offset);
        $colPage = Generic::fillItIfEmpty($colPage, $this->colPage);
        $nextPage = Generic::fillItIfEmpty($nextPage, $this->nextPage);

        $paging = $this->paging->createPage($sum, $offset, PAGES_LIMIT, $nextPage, 10, $colPage);

        return $paging;
    }

    public function UploadFileCSV($file, $filename) {
        $this->load->library('upload');

        $data = array();

        if (!empty($_FILES[$file]['name'])) {
            $config = array();

            $config['upload_path'] = './ibank';
            $config['allowed_types'] = 'csv|doc|pdf|txt|xls';
            $config['file_name'] = $filename;
            $config['max_size'] = '5000000';
            $config['max_width'] = '1024';
            $config['max_height'] = '768';

            $this->upload->initialize($config);

            if ($this->upload->do_upload($file)) {
                $data['uploadData'] = $this->upload->data();
            }
            else {
                $data['errorUpload'] = $this->upload->display_errors() . "</br>";
            }
        }
        else {
            $data['errorUpload'] = "Tidak ditemukan File yang akan diupload.";
        }

        return $data;
    }

    public function ReadFileCSV($filecsv) {
        $content = FALSE;
        $fileContent = file($filecsv);

        foreach ($fileContent as $line) {
            if ($line != '') {
                $content[] = $line;
            }
        }
        return $content;
    }

    public function ReadFileCSV2($filecsv) {
        $content = FALSE;

        $fileContentRaw = file_get_contents($filecsv);

        if(preg_match("#\r#", $fileContentRaw)) {
            $fileContent = explode("\r", $fileContentRaw);
        }
        elseif(preg_match("#\n#", $fileContentRaw)) {
            $fileContent = explode("\n", $fileContentRaw);
        }

        foreach ($fileContent as $line) {
            if ($line != '') {
                $content[] = $line;
            }
        }

        return $content;
    }

    public function getFile($tanggal, $bank) {
        $data = array();

        $resultSet = $this->general_model->getFileName($tanggal, $bank);

        $data['fileName'] = $resultSet->result();
        $data['numRows'] = $resultSet->num_rows();

        return $data;
    }

    public function postValue($msg) {
        $content = $msg;

        $len = strlen($content);
        $hosts = "10.0.0.38";

        $this->db->close();

        try {
            $fp = @fsockopen($hosts, '14000');

            if (!$fp) {
                $res = "Error\n";
            }
            else {
                @fputs($fp, "POST " . '/InterfaceKai/InterfaceInsertTransaksi.php/' . " HTTP/1.0\r\n");
                @fputs($fp, "Connection: close\r\n");
                @fputs($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
                @fputs($fp, "Content-Length: $len\r\n\r\n");
                @fputs($fp, $content);

                $reply = array();

                while (!feof($fp)) {
                    $reply[] = @fgets($fp, 12000);
                }

                @fclose($fp);
                $psn = "";

                foreach ($reply as $v) {
                    $psn .= nl2br($v);
                }

                $msg = $psn;
                $res = $reply[9];
            }
        }catch(Exception $e) {

        }

        $this->db->reconnect();

        return $res;
    }

    function __destruct() {
        if($this->log_event != "") {
            if($this->log_data == "") {
                $this->log_data .= $this->uri->segment(1) . "/";
                $this->log_data .= $this->uri->segment(2);
            }

            $audit_trail = array(
                    'log_time'  => date("Y-m-d H:i:s"),
                    'log_aktor' => $this->userauth->getUserID(),
                    'log_event' => $this->log_event,
                    'log_data'  => $this->log_data
            );

            $this->db_audit->insert("audit_trail", $audit_trail);
        }
    }

    function dc_force_download($filename, $view, $data = array()) {
        header('Content-type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.$filename.'.xls"');

        if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE)
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

        header("Content-Transfer-Encoding: binary");
        header('Pragma: no-cache');
        header('Expires: 0');

        $data["is_export"] = 1;

        $this->loadMenuNoHeader($view, $data);
    }
}

?>
